package cn.winstone.handler;

import cn.winstone.config.Config;
import cn.winstone.enums.StatusCodeEnum;
import cn.winstone.scanner.ResourceScanner;
import cn.winstone.scanner.impl.ResourceScannerImpl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author Winstone
 * @date 2020/7/28 - 10:46 下午
 */
public class ResponseHandler {
    public static String BASE_URI = Config.BASE_URI;
    private ResourceScanner scanner = new ResourceScannerImpl(BASE_URI);

    public String getResource(String uri) throws IOException {

        InputStream stream = null;

        if (uri.substring(uri.lastIndexOf('/')).equals("/")) {
            stream = scanner.getDefaultResource();
        } else {
            try {
                stream = (InputStream) scanner.getResource(uri);

            } catch (Exception e) {
                StatusCodeEnum s = (StatusCodeEnum) scanner.getResource(uri);
                return s.toString();
            }
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); // 实例化输入流，并获取网页代码
            String s;
            StringBuilder sb = new StringBuilder();
            while ((s = reader.readLine()) != null) {
                sb.append(s);
            }

            reader.close();
            return sb.toString();
        }catch (Exception e){
            StatusCodeEnum s = (StatusCodeEnum) scanner.getResource(uri);
            return s.toString();
        }

    }

    public String getResponse(String uri,StatusCodeEnum status) throws IOException {
        StringBuilder returnStr = new StringBuilder();
        returnStr.append("HTTP/1.1 "+ status.getCode()+" "+status.getMsg()+ "\r\n");//增加响应消息行
        if (uri.contains(".css")){
            returnStr.append("Content-Type:text/css;charset=UTF-8\r\n");//增加响应消息头
        }else {
            returnStr.append("Content-Type:text/html;charset=UTF-8\r\n");//增加响应消息头

        }
        returnStr.append("\r\n");//空行
        return returnStr.toString();
    }
}
